package com.xxl.job.executor.sample.frameless.test.sellTicketThread;

import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;

public class ExerciseSell {
    public static void main(String[] args) {
        TicketWindow ticketWindow = new TicketWindow(2000);
        ArrayList<Thread> list = new ArrayList<>();
        // 用来存储卖出去多少张票
        //ArrayList<Integer> sellCount = new ArrayList<>();
        Vector<Integer> sellCount = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread t = new Thread(() -> {
                // 分析这里的竞态条件
                int count = ticketWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        list.forEach((t) -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 卖出去的票求和
        System.out.println("卖出去的票求和：" + sellCount.stream().mapToInt(c -> c).sum());
        // 剩余票数
        System.out.println("剩余票数：" + ticketWindow.getCount());
    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}
